var gradeClassMap = new HashMap();
var classGradeMap = new HashMap();
var gradeRuleMap = new HashMap();
var classRuleMap = new HashMap();
var classLessonCountMap = new HashMap(); //班级对应的课时总数

var idNameMap = new HashMap();


function classUnSchedule() {
    /* 年级班级树和班级不排课时间 */
    getGradeRule();
    getClassRule();
    setGradeClassTree();
    getClassTotalLessonCount();
}

function getClassTotalLessonCount() {
    jQuery.ajax({
        type: "GET",
        url: "getClassTotalLessonCount?taskId=" + taskId,
        success: function (res) {
            if (res && res.length > 0) {
                for (var i = 0; i < res.length; i++) {
                    classLessonCountMap.put(res[i].classId, res[i].lessons);
                }
                // 年级所需的课时数 是 年级下面的班级的MAX
                var gradeIds = gradeClassMap.keySet();
                for (var i = 0; i < gradeIds.length; i++) {
                    var classIds = gradeClassMap.get(gradeIds[i]);
                    var max = -1, tmp = -1;
                    for (var j = 0; j < classIds.length; j++) {
                        tmp = classLessonCountMap.get(classIds[j]);
                        if (!isNaN(tmp) && tmp > max) {
                            max = tmp;
                        }
                    }
                    classLessonCountMap.put(gradeIds[i], max);
                }
            }
        }
    });
}
/**
 * 检查这个班的课时数总数是不是足够
 * return true if and only if it's ok
 * @param classId
 */
function lessonCountCheck(classId, isClassId) {
    var count = classLessonCountMap.get(classId);
    if (isNaN(count) || count < 0) {
        return true; //ok
    }
    var gradeId = !isClassId ? classId : classGradeMap.get(classId);
    var gradeRules = gradeRuleMap.get(gradeId);
    if (gradeRules == null) {
        gradeRules = new Array();
    }
    var classRules = classRuleMap.get(classId);
    if (classRules == null) {
        classRules = new Array();
    }
    for (var i = 0; i < gradeRules.length; i++) {
        if (!classRules.contains(gradeRules[i])) {
            classRules.push(gradeRules[i]);
        }
    }
    var total = lessonsPerDay * defaultDaysPerWeek - classRules.length;
    return total > count;

}
/*得到年级规则*/
function getGradeRule() {
    jQuery.ajax({
        type: "GET",
        url: "getUnScheduleGlobalClassTime?taskId=" + taskId,
        cache: false,
        async: false,
        success: function (msg) {
            var message = JSON.parse(msg);
            var retData = message.data;
            if (retData != null) {
                var length = retData.length;
                for (var i = 0; i < length; i++) {
                    gradeRuleMap.put(retData[i].id, retData[i].time.split(','));
                }
            }
        }
    });
}

/*得到班级规则*/
function getClassRule() {
    jQuery.ajax({
        type: "GET",
        url: "getUnScheduleClassTime?taskId=" + taskId,
        cache: false,
        async: false,
        success: function (msg) {
            var message = JSON.parse(msg);
            var retData = message.data;
            if (retData != null) {
                var length = retData.length;
                for (var i = 0; i < length; i++) {
                    classRuleMap.put(retData[i].id, retData[i].time.split(','));
                }
            }
        }
    });
}

function setGradeClassTree() {
    jQuery.ajax({
        type: "GET",
        url: "/m/jsondata/getGradesAndClasses?taskId=" + taskId,
        cache: false,
        async: false,
        success: function (msg) {
            var message = JSON.parse(msg);
            var retData = message.data;
            if (retData != null) {
                var length = retData.length;
                var root = $("#mainNav_" + unScheduleRuleType);
                var rootHtml = new Array();
                for (var i = 0; i < length; i++) {
                    var grade = JSON.parse(retData[i].grade);
                    rootHtml.push("<ul id=" + grade.gradeId + ">");
                    rootHtml.push("<i class='glyphicon glyphicon-plus-sign' onclick='toggleTree(" + grade.gradeId + ")'></i>");
                    rootHtml.push("<span id='node_grade_" + grade.gradeId + "' onclick='javascript:getGradeRuleById(" + grade.gradeId + ")'>" + grade.gradeName + "</span>");
                    idNameMap.put(grade.gradeId, grade.gradeName);
                    var classes = JSON.parse(retData[i].classes);
                    var classesLength = classes.length;
                    var classIdArr = new Array();
                    for (var j = 0; j < classesLength; j++) {
                        rootHtml.push("<li id='node_class_" + classes[j].classId + "' onclick='javascript:getClassRuleById(" + classes[j].classId + ")'>");
                        rootHtml.push("<span>" + classes[j].className + "</span>");
                        rootHtml.push("</li>");
                        classIdArr.push(classes[j].classId);
                        classGradeMap.put(classes[j].classId, grade.gradeId);
                        idNameMap.put(classes[j].classId, classes[j].className);
                    }
                    rootHtml.push("</ul>");
                    gradeClassMap.put(grade.gradeId,
                        classIdArr);
                }
                root.html(rootHtml.join(""));
            }
        }
    });
}

function getGradeRuleById(gradeId) {
    clearTimeTable();
    $("[id*='node_']").removeClass('selected_node');
    $("#node_grade_" + gradeId).addClass('selected_node');

    selectedNodeType = "grade";
    selectedNodeValue = gradeId;
    // 打印grade下面的class
    var gradeTimeArr = gradeRuleMap.get(gradeId);
    if (gradeTimeArr != null) {
        var length = gradeTimeArr.length;
        for (var i = 0; i < length; i++) {
            $("#td_" + gradeTimeArr[i]).html("不排课");
        }
    }
    //show the tag
    getGradeTagById(gradeId);
}

function setGradeRule(gradeId, timeIndex, isUnSchedule) {
    /* 同时年级本身也维护timeIndex */
    var gradeTimeArr = gradeRuleMap.get(gradeId);
    if (gradeTimeArr == null) {
        if (isUnSchedule == true) {
            gradeTimeArr = new Array();
            gradeTimeArr.push(timeIndex);
            gradeRuleMap.put(gradeId, gradeTimeArr);
        }
    } else {
        if (isUnSchedule == true) {
            if (!gradeTimeArr.contains(timeIndex)) {
                gradeTimeArr.push(timeIndex);
            }
        } else {
            if (gradeTimeArr.contains(timeIndex)) {
                gradeTimeArr.remove(timeIndex);
            }
        }
    }
}

function getClassRuleById(classId) {
    clearTimeTable();
    //标识选中样式
    $("[id*='node_']").removeClass('selected_node');
    var classLi = $("#node_class_" + classId);
    classLi.addClass('selected_node');
    //标识选中，并显示不排课
    selectedNodeType = "class";
    selectedNodeValue = classId;

    //首先显示年级不排课并灰掉不可点
    var gradeId = classLi.parent("ul").attr("id");
    var gradeTimeArr = gradeRuleMap.get(gradeId);
    if (gradeTimeArr != null) {
        var length = gradeTimeArr.length;
        for (var i = 0; i < length; i++) {
            $("#td_" + gradeTimeArr[i]).html("年级不排课");
            $("#td_" + gradeTimeArr[i]).addClass("disabledTd");
            $("#td_" + gradeTimeArr[i]).attr("disabled", true);
        }
    }

    //然后显示班级不排课
    var classTimeArr = classRuleMap.get(classId);
    if (classTimeArr != null) {
        var length = classTimeArr.length;
        for (var i = 0; i < length; i++) {
            $("#td_" + classTimeArr[i]).html("不排课");
        }
    }
    // show tags
    getClassTagById(classId);
    getGradeTagById(gradeId);

    setUnScheduleAll();
}

function setClassRule(classId, timeIndex, isUnSchedule) {
    var classTimeArr = classRuleMap.get(classId);
    if (classTimeArr == null) {
        if (isUnSchedule == true) {
            var arr = new Array();
            arr.push(timeIndex);
            classRuleMap.put(classId, arr);
        }
    } else {
        if (isUnSchedule == true) {
            if (!classTimeArr.contains(timeIndex)) {
                classTimeArr.push(timeIndex);
            }
        } else {
            if (classTimeArr.contains(timeIndex)) {
                classTimeArr.remove(timeIndex);
            }
        }
    }
}

/*生成班级不排课时间的json*/
function toClassString() {
    var array = new Array();
    classRuleMap.forEach(function (key, valueArr) {
        var rule = {};
        rule["id"] = key;
        var temp = $.map(valueArr, function (value, index) {
            return [value];
        });
        if (temp != null && temp.length > 0) {
            rule["time"] = temp.toString();
            rule["type"] = "-";
            array.push(rule);
        }
    })
    return JSON.stringify(array);
}

/*生成全校班级（即年级）不排课时间的json*/
function toGlobalClassString() {
    var array = new Array();
    gradeRuleMap.forEach(function (key, valueArr) {
        var rule = {};
        rule["id"] = key;
        var temp = $.map(valueArr, function (value, index) {
            return [value];
        });
        if (temp != null && temp.length > 0) {
            rule["time"] = temp.toString();
            rule["type"] = "-";
            array.push(rule);
        }
    })
    return JSON.stringify(array);
}

function isConflictWithSubclass(gradeId, timeIndex) {
    var subclassIds = gradeClassMap.get(gradeId);
    if (subclassIds != null) {
        var res = new Array();
        for (var i = 0; i < subclassIds.length; i++) {
            var classRuleArr = classRuleMap.get(subclassIds[i]);
            if (classRuleArr != null && classRuleArr.contains(timeIndex)) {
                res.push(subclassIds[i]);
            }
        }
        return res;
    }
    return null;
}